﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Dune.Common.ComponentModel
{
    /// <summary>
    /// Summary description for SimpleServiceProvider.
    /// </summary>
    public class SimpleServiceProvider : IServiceProvider, IHostable
    {
        Hashtable services = new Hashtable();
        IHost host;

        public SimpleServiceProvider()
        {
        }

        #region Add/Remove methods

        public void AddService(Type serviceType, object service)
        {
            if (serviceType == null)
                throw new ArgumentException("serviceType");

            if (service == null)
                throw new ArgumentException("service");

            if (services.ContainsKey(serviceType))
            {
                throw new ArgumentException("already exists " + serviceType);
            }

            services[serviceType] = service;

        }

        public void RemoveService(Type serviceType)
        {
            services.Remove(serviceType);
        }

        #endregion

        #region IServiceProvider

        public object GetService(Type serviceType)
        {

            if (services.ContainsKey(serviceType))
            {
                return services[serviceType];
            }

            if (Host != null)
            {
                IServiceProvider provider = Host.GetServiceProvider();
                return provider.GetService(serviceType);
            }

            return null;
        }

        #endregion

        #region IHost

        public IHost Host
        {
            get { return host; }
            set { host = value; }
        }

        #endregion
    }
}
